package com.efounder.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.efounder.adapter.MallSelectionPayMultiAdapter;
import com.efounder.bean.MallSelectionPayMultipleBean;
import com.efounder.bean.MallSelectionPayOrderBean;
import com.efounder.bean.UpdateOrderBadgeEvent;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.mobilemall.R;
import com.efounder.ospopenplanet.wxapi.WXPayEntryActivity;
import com.efounder.presenter.MallVirtualProductSelectionPayPresenter;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.efounder.utils.Utils;
import com.efounder.view.countdownview.CountdownView;
import com.pansoft.mobilemallpay.pays.AliPay;
import com.pansoft.mobilemallpay.pays.OnPayListener;
import com.pansoft.mobilemallpay.pays.PayInter;
import com.pansoft.openplanet.activity.AmountRechargeActivity;
import com.efounder.mvp.base.MvpBaseActivity;
import com.pansoft.openplanet.util.TCMathUtil;
import com.utilcode.util.ConvertUtils;
import com.utilcode.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

/**
 * @author : zzj
 * e-mail : zhangzhijun@pansoft.com
 * date   : 2018/9/17 20:27
 * desc   : 虚拟商品 选择支付 activity
 * version: 1.0
 */
public class MallVirtualProductSelectionPayActivity extends MvpBaseActivity<MallVirtualProductSelectionPayPresenter> implements View.OnClickListener {


    /**
     * recyclerView
     */
    private RecyclerView rvSelectionPay;
    /**
     * 订单提醒文本
     */
    private TextView tvOrderHint;

    private CountdownView cvSelectionPay;
    /**
     * 支付按钮
     */
    private Button btnPay;

    private LinearLayout llTopOrderHint;
    /**
     * 列表适配器
     */
    private MallSelectionPayMultiAdapter mallSelectionPayMultiAdapter;
    /**
     * 订单id，订单金额，订单title
     */
    private String orderAmount, orderTitle;

    private ArrayList<String> orderIds;
    /**
     * 数据集合
     */
    private List<MallSelectionPayMultipleBean> selectionPayMultipleBeans = new ArrayList<>();
    /**
     * 订单详情的数据类
     */
    private MallSelectionPayOrderBean orderDetail;

    private String toAddress;

    @Override
    protected MallVirtualProductSelectionPayPresenter initPresenter() {
        return new MallVirtualProductSelectionPayPresenter(this);
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.mall_activity_selection_pay;
    }

    public static void start(Context context, ArrayList<String> orderId, String orderTitle, String orderAmount) {
        Intent starter = new Intent(context, MallVirtualProductSelectionPayActivity.class);
        starter.putStringArrayListExtra("orderId", orderId);
        starter.putExtra("orderTitle", orderTitle);
        starter.putExtra("orderAmount", orderAmount);
        context.startActivity(starter);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        Bundle bundle = getIntent().getExtras();
        orderIds = bundle.getStringArrayList("orderId");
        orderAmount = bundle.getString("orderAmount");
        orderTitle = bundle.getString("orderTitle");
        findViewById(R.id.title).setVisibility(View.VISIBLE);
        TextView tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(R.string.mall_selection_pay_title);
        tvOrderHint = (TextView) findViewById(R.id.tv_order_hint);
        cvSelectionPay = (CountdownView) findViewById(R.id.cv_selection_pay);
        btnPay = (Button) findViewById(R.id.btn_pay);
        llTopOrderHint = (LinearLayout) findViewById(R.id.ll_top_order_hint);
        llTopOrderHint.setVisibility(View.INVISIBLE);
        tvOrderHint.setVisibility(View.INVISIBLE);
        btnPay.setOnClickListener(this);
        rvSelectionPay = (RecyclerView) findViewById(R.id.mall_rv_selection_pay);
        rvSelectionPay.setLayoutManager(new LinearLayoutManager(this));
        mallSelectionPayMultiAdapter = new MallSelectionPayMultiAdapter(selectionPayMultipleBeans);
        rvSelectionPay.setAdapter(mallSelectionPayMultiAdapter);
        initEvent();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (orderIds != null) {
            //请求订单详情
            presenter.getOrderDetailsData("", orderIds.toString());
        }

//        presenter.pay(EnvironmentVariable.getProperty("tc_ethAddress", ""),"45",orderIds.get(0),goodsId,orderIds.get(0),"1",,EnvironmentVariable.getUserName(),);
    }

    @Override
    public void initEvent() {
        //adapter的点击事件
        mallSelectionPayMultiAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                presenter.onAdapterItemClick(adapter, selectionPayMultipleBeans, position);
            }
        });
        //列表中按钮的点击事件
        mallSelectionPayMultiAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.tv_go_recharge) {
                    MallSelectionPayMultipleBean.SelectionPay selectionPay = selectionPayMultipleBeans.get(position).getSelectionPay();
                    AmountRechargeActivity.start(MallVirtualProductSelectionPayActivity.this, selectionPay.getTitle(), selectionPay.getTokenTypeId());
                }
            }
        });

    }


    @Override
    public void onClick(View v) {
        int i = v.getId();
        //支付按钮点击事件
//        if (i == R.id.btn_pay) {
//            if (orderNumber == null) {
//                ToastUtils.showShort(getString(R.string.mall_selection_pay_order_hint));
//                return;
//            }
        if (selectionPayMultipleBeans.size() == 0) {
            ToastUtils.showShort(ResStringUtil.getString(R.string.wrchatview_data_error));
            return;
        }
        MallSelectionPayMultipleBean selectionPayBean = selectionPayMultipleBeans.get(0);
        //当前是否选择了支付方式
        if (selectionPayBean != null) {
            if (orderDetail != null) {
                if (orderDetail.getPrePayInfo().getTokenUseArray().get(0).getTokenTypeId().equals("6")) {
                    //观影券
                    toAddress = "0xf895b1b7500b1d282ef6c6d42ae5ce8be1d53fee";
                } else if (orderDetail.getPrePayInfo().getTokenUseArray().get(0).getTokenTypeId().equals("7")) {
                    //参演券
                    toAddress = "0x831ed6194d43578e1fc0253a88f11851fba4adc2";
                }
                if(selectionPayBean.getSelectionPay().getSurplusNum() == null){
                    ToastUtils.showShort(getString(R.string.mall_selection_pay_balance_hint));
                    return;
                }
                if (selectionPayBean.getSelectionPay().getSurplusNum() != null && !selectionPayBean.getSelectionPay().getSurplusNum().equals("")) {
                    if (Double.valueOf(selectionPayBean.getSelectionPay().getSurplusNum()) < Double.valueOf(orderAmount)) {
                        ToastUtils.showShort(getString(R.string.mall_selection_pay_balance_hint));
                        return;
                    }
                }
                //矿工费
                String gasPrice1 = "0.0004";
                EnvironmentVariable.setProperty("mobile_pay_good_price",orderDetail.getPrePayInfo().getTokenUseArray().get(0).getTokenTypeName()+ orderAmount);
                presenter.pay(EnvironmentVariable.getProperty("tc_ethAddress", ""), toAddress,
                        orderDetail.getPrePayInfo().getOrdersTotalPrice() + ""
                        , orderDetail.getPrePayInfo().getContractArray().get(0).getOrderBh().trim()
                        , orderDetail.getPrePayInfo().getContractArray().get(0).getGoodBh(), orderDetail.getPrePayInfo().getContractArray().get(0).getOrderBh().trim()
                        , orderDetail.getPrePayInfo().getContractArray().get(0).getGoodNum() + "", EnvironmentVariable.getUserName(), orderDetail.getPrePayInfo().getContractArray().get(0).getToAddress(), gasPrice1);


            } else {
                ToastUtils.showShort(getString(R.string.mall_selection_pay_order_hint));
            }

        }
    }


    /**
     * 获取订单信息成功
     *
     * @param mallSelectionPayOrderBea 订单详情数据
     */

    public void getDataSuccess(MallSelectionPayOrderBean mallSelectionPayOrderBea, List<MallSelectionPayMultipleBean> mallSelectionPayMultipleBeans) {
        if (mallSelectionPayOrderBea != null) {
            this.orderDetail = mallSelectionPayOrderBea;
            selectionPayMultipleBeans.clear();
            selectionPayMultipleBeans.addAll(mallSelectionPayMultipleBeans);

            presenter.getBalancefromServer(orderDetail.getPrePayInfo().getContractArray().get(0).getToAddress());
            orderAmount = TCMathUtil.retainAsignDecimalsWithZero(orderDetail.getPrePayInfo().getOrdersTotalPrice(), 2);
            //设置订单提醒字体颜色高亮
            cvSelectionPay.start(orderDetail.getPrePayInfo().getRemainPayTime());
            String text = String.format(getString(R.string.mall_selection_pay_order_hint3)
                    , orderDetail.getPrePayInfo().getTokenUseArray().get(0).getTokenTypeName() + " " + orderAmount);
            tvOrderHint.setText(Utils.matcherSearchTextSize(getResources().getColor(R.color.op_orange_color)
                    , ConvertUtils.dp2px(16), text, new String[]{orderAmount}));
            llTopOrderHint.setVisibility(View.VISIBLE);
            tvOrderHint.setVisibility(View.VISIBLE);
        }
    }

    public void getBalanceDataSuccess(String balance) {
//        if(selectionPayMultipleBeans.size()>0&&selectionPayMultipleBeans.get(0).getSelectionPay().isPay()){
//            if(Double.valueOf(balance)>Double.valueOf(orderAmount)){
//                selectionPayMultipleBeans.get(0).getSelectionPay().setSelectPayWay(true);
//            }
//        }
        presenter.loadBalanceData(selectionPayMultipleBeans, orderDetail.getPrePayInfo().getOrdersTotalPrice()
                , balance, orderDetail.getPrePayInfo().getTokenUseArray().get(0).getTokenTypeName(), mallSelectionPayMultiAdapter);
    }

    /**
     * 支付成功
     *
     * @param finalPay 支付
     */

    public void paySuccess(PayInter finalPay) {
        //如果是订单列表了付款，需要通知订单角标刷新
        EventBus.getDefault().post(new UpdateOrderBadgeEvent());
        Intent intent = new Intent(activity, MallGeneralOrderActivity.class);
        intent.putExtra("targetIndex", 0);
        startActivity(intent);
        finish();
    }

    /**
     * 支付失败
     *
     * @param finalPay 支付方式
     * @param msg      失败信息
     * @param code     失败code
     */

    public void payFailed(PayInter finalPay, String msg, int code) {
        if (code == OnPayListener.ERROR) {
            ToastUtil.showToast(MallVirtualProductSelectionPayActivity.this, msg);
            if (finalPay instanceof AliPay) {
                //阿里支付成功后需要手动跳转到支付成功界面
                //微信会自动跳转到成功界面;
                Intent intent = new Intent(MallVirtualProductSelectionPayActivity.this, WXPayEntryActivity.class);
                intent.putExtra("type", "ali");
                intent.putExtra("status", "failure");
                startActivity(intent);
            } else if (finalPay == null) {
                Intent intent = new Intent(MallVirtualProductSelectionPayActivity.this, WXPayEntryActivity.class);
                intent.putExtra("type", "ali");
                intent.putExtra("status", "failure");
                startActivity(intent);
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();


    }
}
